<?php
namespace App\Http\Controllers\Admin;

use App\Services\Admin\SceneService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;

class SceneController extends BaseController
{
    //场景

    public function __construct(SceneService $service)
    {
        $this->db = $service;
    }

    /**
     * 场景列表
     */
    public function getIndex(Request $request)
    {
        $pages['start'] = $request->post('pageStart', 0);
        $pages['limit'] = $request->post('pageLimit', 10);
        $rst = $this->db->getIndex($pages);
        if ($rst['code']!=0) {
            return $this->toJson(-2, $rst['msg']);
        }
        return $this->toJson(0, '', $rst['data'], $rst['total']);
    }

    //场景修改
    public function modify(Request $request)
    {
        //字段验证
        $this->validate($request, [
            'id' => 'required',
            'title' => 'required|min:2|max:255',
        ], [
            'id.required' => '场景ID必须的',
            'title.required' => '场景名称必须的',
            'title.min' => '场景名称不能少于 :min 字符',
            'title.max' => '场景名称不能多于 :max 字符',
        ]);
        $id = $request->post('id', 0);
        $pas['title'] = $request->post('title', '');
        $attrs = $request->post('attr_str', '');
        $thumb = $request->post('thumb', '');
        $icon = $request->post('icon', '');
        if ($thumb) {
            if (substr($thumb, 0, 5) == 'data:') {
                $pas['thumb'] = Upload::getPathByBase64($thumb);
            } else {
                $pas['thumb'] = $thumb;
            }
        }
        if ($icon) {
            if (substr($icon, 0, 5) == 'data:') {
                $pas['icon'] = Upload::getPathByBase64($icon);
            } else {
                $pas['icon'] = $icon;
            }
        }
        if ($id) {
            $res = $this->db->modify($id, $pas, $attrs);
        } else {
            $res = $this->db->add($pas, $attrs);
        }
        if ($res['code']!=0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //场景删除
    public function del(Request $request)
    {
        //字段验证
        $this->validate($request, [
            'id' => 'required',
        ], [
            'id.required' => '场景ID必须的',
        ]);
        $id = $request->post('id', 0);
        $res = $this->db->del($id);
        if ($res['code']!=0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }
}